package xml.cast;

import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
//import java.io.BufferedReader;
//import java.io.InputStreamReader;
//import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

import javax.swing.Box;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;


public class MessageServer extends JFrame {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	Thread serverThread; // the thread we will use for the server

	// GUI stuff
	private JLabel lblPort;
	private JTextField txtPort;
	private JButton btnGo;
	//private JScrollPane paneContent;
	private JTextArea txtLog;

	public static void main(String args[]) {
		new MessageServer();
	}

	/** Creates new form WebServer1 */
	public MessageServer() {
		this.setTitle("Message server");
		Container pane = getContentPane();
		pane.setLayout(new BorderLayout());
		
		Box topBox = Box.createHorizontalBox();
		pane.add(topBox, BorderLayout.NORTH);

		lblPort = new JLabel("Port");
		topBox.add(lblPort);
		txtPort = new JTextField("90");
		txtPort.setPreferredSize(new Dimension(150, 21));
		topBox.add(txtPort);
		btnGo = new JButton("Go");
		topBox.add(btnGo);
		btnGo.addMouseListener(new MouseAdapter() {
			public void mouseClicked(MouseEvent evt) {
				btnGoMouseClicked(evt);
			}
		});
		
		JScrollPane paneContent = new JScrollPane();
		paneContent.setPreferredSize(new Dimension(300, 300));
		txtLog = new JTextArea();
		txtLog.setFont(new Font("Courier New", 0, 12));
		paneContent.setViewportView(txtLog);
		pane.add(paneContent, BorderLayout.CENTER);
		
		addWindowListener(new WindowAdapter() {
			public void windowClosing(WindowEvent evt) {
				exitForm(evt);
			}
		});

		pack();
		setVisible(true);
	}

	private void exitForm(WindowEvent evt) {
		System.exit(0);
	}

	private void btnGoMouseClicked(MouseEvent evt) {
		// Create the server thread and specify its contents
		serverThread = new Thread() {
			public void run() {
				try {
					int port = Integer.parseInt(txtPort.getText());

					ServerSocket listener = new ServerSocket(port, 10, null);
					txtLog.setText("Listening on port " + txtPort.getText() + "\n");

					while (true) {
						// The "accept" method waits for a request, then creates a socket
						// connected to the requesting client
						Socket client = listener.accept();

						txtLog.setText(txtLog.getText() + "Request from client "
								+ client.getInetAddress().toString() + " for server (me) "
								+ client.getLocalAddress().toString() + "\n");

						// Answer messages until the client signs off
						Message.MessageType lastMessageType = null;
						while (lastMessageType != Message.MessageType.Goodbye) {
							// Read a message from the client
							Message msgIn = Message.receive(client);
							lastMessageType = msgIn.getType();
							txtLog.setText(txtLog.getText() + "Message received from client: "
									+ msgIn.toString()  + "\n");						
							
							// Send an answer to the client
							Message msgOut = null;
							switch (lastMessageType) {
							case Hello:
								msgOut = new Message(Message.MessageType.Hello);
								break;
							case NewClient:
								if(msgIn.getObjectToSend().getObjectType() == 0)System.out.println(((Hexagram)msgIn.getObjectToSend()).getTitle());
								else if(msgIn.getObjectToSend().getObjectType() == 1)System.out.println(((User)msgIn.getObjectToSend()).getName());
								msgOut = new Message(Message.MessageType.NewClientAccepted);
								msgOut.setObjectToSend(msgIn.getObjectToSend());
								break;
							case Goodbye:
								msgOut = new Message(Message.MessageType.Goodbye);
								break;
							}
							msgOut.send(client);
							txtLog.setText(txtLog.getText() + "reply sent\n");
						}						

						// Close the socket
						client.close();
					}
				} catch (Exception e) {
					System.err.println(e);
				}
			}
		};

		serverThread.start();
	}
}
